<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Cartpool {
	
	public $CI;
	
	public $id;
	public $email;
	public $name;
	public $group;
	

	public $errors = array(
		"login_emailError" => "wrong email addres",
		"login_userNotFound" => "User was not found, try again",
		"login_succes" => "logged in succesfully"
	);
	
	function Cartpool() {
		$this->CI =& get_instance(); //pass codeIgnitor as a reference, in a controller $this is CI
		$this->CI->load->library('session');
		$this->CI->load->database();
		$this->CI->load->model('user');
		$this->CI->load->model('product');
		$this->CI->load->model('shoppingcart');
		$this->CI->load->model('products_in_cart');
		
		$this->id = $this->CI->session->userdata('id');
		$this->email = $this->CI->session->userdata('email');
		$this->name = $this->CI->session->userdata('name');
		$this->group = $this->CI->session->userdata('group');
	}
	
	private function getLoggedInUser(){
		$user = new $this->CI->user();
		$user->id = $this->id;
		$users = $user->get();
		return $users;
	}
	

	public function getGroupMembers(){
		$user = new $this->CI->user();
		$user->group = $this->group;
		//$user->order_by = 'saldo ASC';
		$users = $user->get();
		
		// overwrite users saldo here?
		if($users){
			foreach($users as $user){		
				// the sum of all products once bought by the user
				$productInCart = $this->getTotalInCartByCustomer($user->name);
				
				// the sum of all shoppinglists once paid by the user
				$paidShoppingList = $this->getTotalInPaidShoppingList($user->name);
				$user->saldo = (-$productInCart->total) + $paidShoppingList;
			}
			function cmpSaldo($a,$b) {
				$a = $a->saldo;
				$b = $b->saldo;
				if ($a == $b) {
					return 0;
				}
				return ($a < $b) ? -1 : 1;
			}
			usort($users, "cmpSaldo");
		}

		
		return $users;
	}


	private function getTotalInPaidShoppingList($name){
		$shoppingcart = new $this->CI->shoppingcart();
		$shoppingcart->group = $this->group;
		$shoppingcart->paidby = $name;
		$total = $shoppingcart->getSumTotal();
		return $total[0]->total;
	}
	
	
	private function getProducts(){
		$product = new $this->CI->product();
		$product->group = $this->group;
		$product->order_by = 'rayon DESC';
		$products = $product->get();
		return $products;
	}
	
	public function login($email, $password){
		$user = new $this->CI->user();
		$user->email = $email;
		$user->password = $password;		
		
		$users = $user->get();
		
		if($users){
			//echo $users[0]->group . " in users";
			$this->id = $users[0]->id;
			$this->email = $users[0]->email;
			$this->name = $users[0]->name;
			$this->group = $users[0]->group;
			
			$sessionData = array(
				'id'		=> $users[0]->id, 
				'name'		=> $users[0]->name, 
				'email'		=> $users[0]->email, 
				'group'		=> $users[0]->group, 
				'offset'	=> 1, 
				'logged_in'	=> TRUE
			);
			$this->CI->session->set_userdata($sessionData);
			return "login_succes";
		}else{
			return "login_userNotFound";
		}
	}
	
	public function get_user_by_email($email){
		$user = new $this->CI->user();
		$user->email = $email;
		$users = $user->get();
		
		if($users){		
			return TRUE;
		}else{
			return FALSE;
		}
	}
		
	public function register_user($email, $name, $groupname, $password){
		$user = new $this->CI->user();
		$user->group = $groupname;
		$user->email = $email;
		$user->password = $password;
		$user->name = $name;
		$user->saldo = 0;
		$user->save();
	}
	
	public function findProducts($search){
		$product = new $this->CI->product();
		$product->group = $this->group;
		$product->order_by = 'rayon DESC';
		$products = $product->search($search);
		return $products;
	}
	
	public function createProduct($name, $category){
		$product = new $this->CI->product();
		$product->group = $this->group;
		$product->name = $name;
		$product->rayon = $category;
		$product->save();
	}
	
	public function getShoppingList($offset){
		//$this->CI->benchmark->mark('code_start');
		
		//get the last shoppingcart
		$shoppingcart = new $this->CI->shoppingcart();
		$shoppingcart->group = $this->group;
		$shoppingcart->limit = 1;

		$shoppingcart->offset = $offset;
		
		$shoppingcart->order_by = "id DESC";
		$shoppingcarts = $shoppingcart->get();
		
		if($shoppingcarts){
			$shoppingcarts[0]->products = $this->getProductsInCart($shoppingcarts[0]->id);		
			//get the amount of lists!
			$shoppingcarts[0]->amount = $this->CI->shoppingcart->count_all();
			
			$total = 0;
			if($shoppingcarts[0]->products){
				foreach($shoppingcarts[0]->products as $product){
					$total += ($product->qty * $product->price);
				}
			}
			
			$shoppingcarts[0]->total = $total;
			$shoppingcarts[0]->offset = $offset;
			//$this->CI->benchmark->mark('code_end');
			return $shoppingcarts;
		}else{
			return array();
		}

		
	}

	public function closeShoppingList($listId){
		$this->CI->load->helper('date');
		//get the last shoppingcart
		$shoppingcart = new $this->CI->shoppingcart();
		$shoppingcart->id = $listId;
		$currentList = $shoppingcart->get();
	
		
		$products = $this->getProductsInCart($listId);
		$total = 0;
		foreach($products as $product){
			$total += ($product->qty * $product->price);
		}

		date_default_timezone_set('Europe/Paris');
		$datestring = "%Y-%m-%d %H:%i:%a";
		$time = time();

		$shoppingcart->closed = mdate($datestring, $time);
		
		if(!$currentList->paidby){
			$shoppingcart->paidby = $this->name;
		}
		
		$shoppingcart->total = $total;
		
		$shoppingcart->save();
	}

	public function updateShoppingListTotal($listId){
		$shoppingcart = new $this->CI->shoppingcart();
		$shoppingcart->id = $listId;
		$currentList = $shoppingcart->get();
	
		$products = $this->getProductsInCart($listId);
		$total = 0;
		foreach($products as $product){
			$total += ($product->qty * $product->price);
		}
		
		if($total == 0){
			$total = "0.00";
		}
		
		$shoppingcart->total = $total;		
		$shoppingcart->save();
	}

	public function ImPayingForShoppingList($listId){
		$shoppingcart = new $this->CI->shoppingcart();
		$shoppingcart->id = $listId;
		$currentList = $shoppingcart->get();
	
		$products = $this->getProductsInCart($listId);
		$total = 0;
		foreach($products as $product){
			$total += ($product->qty * $product->price);
		}

		$shoppingcart->paidby = $this->name;
		
		if($total == 0){
			$total = "0.00";
		}
		
		$shoppingcart->total = $total;		
		$shoppingcart->save();
	}

	public function fixShoppingLists(){
		$shoppingcart = new $this->CI->shoppingcart();
		$currentList = $shoppingcart->get();
		foreach($currentList as $list){
			echo $list->id;
			$products = $this->getProductsInCart($list->id);
			$total = 0;
			foreach($products as $product){
				$total += ($product->qty * $product->price);
			}
				
			if($total == 0){
				$total = "0.00";
			}
			
			$currentCart = new $this->CI->shoppingcart();
			$currentCart->id = $list->id;
			$currentCart->total = $total;		
			$currentCart->save();
		}
	}
	
	public function fixOrderTotals(){
		$products_in_cart = new $this->CI->products_in_cart();
		$products_in_cart->product = null;
		$products_in_cart->order_by = 'rayon DESC, product DESC';
		$products_in_cart_array = $products_in_cart->get();
		foreach($products_in_cart_array as $product){
			$total = ($product->qty * $product->price);
			$currentProduct = new $this->CI->products_in_cart();
			$currentProduct->id = $product->id;
			$currentProduct->total = $total;		
			$currentProduct->save();
		}		
	}

	private function getProductsInCart($id){
		$products_in_cart = new $this->CI->products_in_cart();
		$products_in_cart->product = null;
		$products_in_cart->shoppingcartId = (int)$id;
		$products_in_cart->order_by = 'rayon DESC, product DESC';
		$products_in_cart_array = $products_in_cart->get();
		if($products_in_cart_array){
			return $products_in_cart_array;		
		}else{
			return array();
		}
	}

	private function getTotalInCartByCustomer($name){
		$products_in_cart = new $this->CI->products_in_cart();
		$products_in_cart->product = null;
		$products_in_cart->customer = $name;
		$products_in_cart->group = $this->group;
		$products_in_cart->limit = 1;
		$products_in_cart_array = $products_in_cart->getSumTotal();
		return $products_in_cart_array[0];
	}
	
	public function increaseQtyOnProduct($productId){
		$products_in_cart = new $this->CI->products_in_cart();
		$products_in_cart->product = null;
		$products_in_cart->id = (int)$productId;
		$currentProduct = $products_in_cart->get();
		$products_in_cart->qty = (int)$currentProduct->qty + 1;
		$products_in_cart->total = ($products_in_cart->qty * $currentProduct->price);
		$products_in_cart->save();
		
		//check if the current list is closed
		$shoppingcart = new $this->CI->shoppingcart();
		$shoppingcart->id = $currentProduct->shoppingcartId;
		$currenList = $shoppingcart->get();
		if($currenList->paidby){
			$this->updateShoppingListTotal($currentProduct->shoppingcartId);
		}
	}

	public function addCommentOnProduct($productId){
		$products_in_cart = new $this->CI->products_in_cart();
		$products_in_cart->product = null;
		$products_in_cart->id = (int)$productId;
		$products_in_cart->comments = "enter your comment here";
		$products_in_cart->save();
	}

	public function updateCommentOnProduct($productId, $comment){
		$products_in_cart = new $this->CI->products_in_cart();
		$products_in_cart->product = null;
		$products_in_cart->id = (int)$productId;
		if($comment == ""){
			$comment = " ";
		}
		$products_in_cart->comments = $comment;
		$products_in_cart->save();
	}

	public function decreaseQtyOnProduct($productId){
		$products_in_cart = new $this->CI->products_in_cart();
		$products_in_cart->product = null;
		$products_in_cart->id = (int)$productId;
		$currentProduct = $products_in_cart->get();
		if((int)$currentProduct->qty <= 1){
			$products_in_cart->delete();				
		}else{
			$products_in_cart->qty = (int)$currentProduct->qty - 1; 
			$products_in_cart->total = ($products_in_cart->qty * $currentProduct->price);
			$products_in_cart->save();	
		}
		
	
		//check if the current list is closed
		$shoppingcart = new $this->CI->shoppingcart();
		$shoppingcart->id = $currentProduct->shoppingcartId;
		$currenList = $shoppingcart->get();
		if($currenList->paidby){
			$this->updateShoppingListTotal($currentProduct->shoppingcartId);
		}
	}
	public function deleteProductInCart($productId){
		$products_in_cart = new $this->CI->products_in_cart();
		$products_in_cart->product = null;
		$products_in_cart->id = (int)$productId;
		$products_in_cart->delete();				
	}
	
	public function createProductInCart($shoppingCartId, $product, $rayon){
		
		//echo "niuwe: " . $shoppingCartId;
		
		$shoppingcart = new $this->CI->shoppingcart();
		$shoppingcart->id = $shoppingCartId;
		$shoppingcart->group = $this->group;
		$currentList = $shoppingcart->get();
		
		if($shoppingCartId != "" && $currentList && $currentList->closed == ""){
			$products_in_cart = new $this->CI->products_in_cart();
			$products_in_cart->shoppingcartId = $shoppingCartId;
			$products_in_cart->group = $this->group;
			$products_in_cart->customer = $this->name;
			$products_in_cart->product = $product;
			$products_in_cart->rayon = $rayon;
			//echo "saving";
			$products_in_cart->save();
			return true;
		}else{
			//the current list is closed, check for an open list
			$shoppingListArray = $this->getShoppingList(0);
			$shoppingList = false;
			if(count($shoppingListArray) > 0){
				$shoppingList = $shoppingListArray[0];			
			}
			if($shoppingList && $shoppingList->closed == ""){
				//echo "found open list";
				return $this->createProductInCart($shoppingList->id, $product, $rayon);
			}else{
				//echo "creating new list";
				//no open list, customer want to create a new list
				$this->CI->load->helper('date');
				//get the last shoppingcart
				$newshoppingcart = new $this->CI->shoppingcart();
				date_default_timezone_set('Europe/Paris');
				$datestring = "%Y-%m-%d %H:%i:%a";
				$time = time();	
				$newshoppingcart->created = mdate($datestring, $time);
				$newshoppingcart->group = $this->group;
				if($newshoppingcart->save()){				
					$shoppingcart = new $this->CI->shoppingcart();
					$shoppingcart->group = $this->group;
					$shoppingcart->limit = 1;		
					$shoppingcart->order_by = "id DESC";
					$shoppingcarts = $shoppingcart->get();
							
					return $this->createProductInCart($shoppingcarts[0]->id, $product, $rayon);
				}
			}
		}
	}
	
	public function changePriceOnProduct($productId, $price){
		$products_in_cart = new $this->CI->products_in_cart();
		$products_in_cart->product = null;
		$products_in_cart->id = (int)$productId;
		$currentProduct = $products_in_cart->get();

		$products_in_cart->price = $price;
		$products_in_cart->total = ($currentProduct->qty * $price);
		
		$products_in_cart->save();	

	
		//check if the current list is closed
		$shoppingcart = new $this->CI->shoppingcart();
		$shoppingcart->id = $currentProduct->shoppingcartId;
		$currenList = $shoppingcart->get();
		if($currenList->paidby){
			$this->updateShoppingListTotal($currentProduct->shoppingcartId);
		}
	}

	public function getCartpoolData(){
		return array(
			"sessionData" => $this->CI->session->userdata,
			"products" => $this->getProducts(),
			"groupMembers" => $this->getGroupMembers(),
			"shoppingList" => $this->getShoppingList(0),
			"user" => $this->getLoggedInUser()
		);
	}
}
?>